<template>
    <div style="height:100%">
        <div class="move-box">
            <RiskLeftModule
                v-model="leftKey"
                @on-submit="submitInput"
                @on-handleNode="clickNode"
                :placeholders="leftplaceholder"
                :treeData="treeData"
                :leftHeight="leftHgt"
                :currentKey="1"
                :defaultExpandedKeys="defaultExpandedKeys"
            >
                <template slot="ltitle">自定义证券池信息</template>
            </RiskLeftModule>
            <template v-if="cutInfo === '外部'">
                <RiskRightModule02>
                    <p slot="rtitle">自定义证券池信息</p>
                    <span slot="button" class="layout01-r-slot">
                        <el-input
                            placeholder="证券池编码/名称"
                            v-model="searchData.textTemp"
                            style="width: 170px"
                            size="mini"
                            key="table2-input1"
                            clearable
                        />
                        <el-select
                            v-model="searchData.typeTemp"
                            placeholder="来源类型"
                            style="width: 110px"
                            size="mini"
                            key="table1-input2"
                            clearable
                        >
                            <el-option value="2" label="恒生-主动" />
                            <el-option value="5" label="恒生-被动" />
                        </el-select>
                        <el-button type="primary" @click="searchPool" size="mini" style="margin-left: 5px" key="table1-btn1">查询</el-button>
                        <el-button type="primary" size="mini" v-authCode.show="B_0142" @click="handleExport">导出</el-button>
                    </span>
                    <slot>
                        <el-table
                            :data="poolData"
                            v-table-top="poolPage.currentPage"
                            border
                            size="mini"
                            style="width: 100%"
                            height="calc(100vh - 135px)"
                            @selection-change="handleSelectionChange"
                            @select-all="handleSelectionChange"
                            @sort-change="handleSort"
                        >
                            <el-table-column align="center" type="selection" width="50" size="mini"> </el-table-column>

                            <el-table-column prop="stGrCustomCode" label="自定义证券池编码" width="150" show-overflow-tooltip> </el-table-column>
                            <el-table-column prop="stGrCustomName" label="自定义证券池名称" show-overflow-tooltip> </el-table-column>
                            <el-table-column prop="sourceCustomType" label="数据来源" width="120" show-overflow-tooltip> </el-table-column>
                            <el-table-column
                                prop="dtCtDate"
                                label="添加日期"
                                show-overflow-tooltip
                                align="center"
                                width="180"
                                sortable
                            >
                                <template slot-scope="scope">
                                    <span>{{ dateFormat(scope.row.dtCtDate) }} {{ timeFormat(scope.row.dtCtTime) }}</span>
                                </template>
                            </el-table-column>
                            <!-- <el-table-column
                                prop="dtCtTime"
                                label="添加时间"
                                width="120"
                                show-overflow-tooltip
                                :formatter="formatterTime"
                                align="center"
                            >
                            </el-table-column> -->
                            <el-table-column prop="dtCtUser" label="添加者" width="100" show-overflow-tooltip v-if="showParamByDocking()">
                            </el-table-column>
                            <el-table-column label="操作" width="120">
                                <template slot-scope="scope">
                                    <RiskIconButton
                                        type="primary"
                                        icon="el-icon-edit"
                                        topTitle="编辑证券池"
                                        v-authCode="B_0120"
                                        :disabled="scope.row[sourceCustomType] !== '1'"
                                    ></RiskIconButton>
                                    <RiskIconButton
                                        type="danger"
                                        icon="el-icon-delete"
                                        topTitle="删除"
                                        v-authCode="B_0119"
                                        :disabled="scope.row[sourceCustomType] !== '1'"
                                    ></RiskIconButton>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="block">
                            <risk-pagination :paging="poolPage" @page-change="currentChange"></risk-pagination>
                        </div>
                    </slot>
                    <!-- <risk-table :msg="stockCustomPoolListMsg"></risk-table> -->
                </RiskRightModule02>
            </template>
            <template v-else>
                <RiskRightModule v-model="rightKey2" :rightPlace="rightplaceHolder2" :rightHeight="leftHgt" @on-keyup="searchPoolDetail">
                    <p slot="rtitle">自定义证券池明细信息</p>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" @click="searchPoolDetail">查询</el-button>
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" v-authCode.show="B_0143" @click="handleExportDetail">导出明细</el-button>
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" v-authCode.show="B_0142" @click="layoutDialog = true">布局设置</el-button>
                    </span>
                    <!-- <span slot="button" class="dict-r-slot">
          <el-button type="danger" size="mini" v-authCode.show="B_0122">删除</el-button>
        </span> -->
                    <!-- <risk-table :msg="stockCustomPoolDeatailMsg"></risk-table> -->
                    <el-table
                        :data="poolDetailData"
                        v-table-top="poolPage.currentPage"
                        border
                        size="mini"
                        style="width: 100%"
                        height="calc(100vh - 135px)"
                        @selection-change="handleSelectionDetailChange"
                        @select-all="handleSelectionDetailChange"
                        @sort-change="handleSort1"
                    >
                        <el-table-column align="center" type="selection" width="50" size="mini"> </el-table-column>
                        <template v-for="(item, index) in showFieldList.length ? showFieldList : tableColumns">
                            <el-table-column show-overflow-tooltip :key="index" :label="item.content" :prop="item.id" :render-header="renderHeader" :sortable="item.sortable">
                                <template slot-scope="scope">
                                    <span v-if="item.id === 'stockCustomType'">
                                        {{ StockType[scope.row[item.id]] }}
                                    </span>
                                    <span v-else-if="item.id === 'cateGoryCode'">
                                        {{ CategoryType[scope.row[item.id]] }}
                                    </span>
                                    <span v-else-if="item.id === 'marketCode'">
                                        {{ MarketType[scope.row[item.id]] }}
                                    </span>
                                    <span v-else-if="item.id === 'calculateValue' || item.id === 'thresholdValue'">{{
                                        scope.row[item.id] != undefined ? numberFormat(scope.row[item.id]) : '--'
                                    }}</span>
                                    <!-- <span v-else-if="item.id === 'dtCtTime' || item.id === 'dtCtTime'" style="display:block; text-align:center">{{
                                        scope.row[item.id] || '--'
                                    }}</span> -->
                                    <span v-else-if="item.id === 'dtCtDate'" style="display:block; text-align:center">{{
                                        scope.row[item.id] + ' ' + scope.row.dtCtTime || '--'
                                    }}</span>
                                    <span v-else>{{ scope.row[item.id] || '--' }}</span>
                                </template>
                            </el-table-column>
                        </template>
                        <!-- <el-table-column prop="marketCode" label="交易市场" width="150" show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span>{{ MarketType[scope.row.marketCode] }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="stockCode" label="证券代码" width="150" show-overflow-tooltip> </el-table-column>
                    <el-table-column prop="stockNameSt" label="证券简称" width="120" show-overflow-tooltip> </el-table-column>
                    <el-table-column prop="stockName" label="证券全称" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="cateGoryCode" label="资产类别" width="120" show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span>{{ CategoryType[scope.row.cateGoryCode] }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="stockCustomType" label="证券类型" width="100" show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span>{{ StockType[scope.row.stockCustomType] }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="dtCtDate" label="添加日期" width="120" show-overflow-tooltip> </el-table-column>
                    <el-table-column prop="dtCtTime" label="添加时间" width="100" show-overflow-tooltip> </el-table-column>
                    <el-table-column prop="dtCtUser" label="添加者" width="100" show-overflow-tooltip> </el-table-column> -->
                    </el-table>
                    <div class="block">
                        <risk-pagination :paging="detailPage" @page-change="currentDetailChange"></risk-pagination>
                    </div>
                </RiskRightModule>
            </template>
        </div>
        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            table-name="STOCK_CUSTOM_POOL"
            @on-submit="onSubmit"
        />
    </div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import RiskLeftModule from '@/common/components/risk-left-module.vue';
import RiskRightModule from '@/common/components/risk-right-module.vue';
import RiskRightModule02 from '@/common/components/risk-right-module02.vue';
import RiskPagination from '@/common/components/risk-pagination.vue';

import RiskIconButton from '@/common/components/risk-icon-button.vue';
import RiskTable from '@/common/components/risk-table.vue';
import { DialogVO } from '@yhfin/biz';
import { downLoadFile } from '@/utils/request';
import { getCurrentPageData, numberFormat, formatterDate, formatterTime, formatter, formatterNumber, showParamByDocking, timeFormat, dateFormat } from '@/utils/tools';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';

type TFieldItem = { id: string; content: string };

export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}
@Component({
    name: 'StockCustomPool',
    components: {
        RiskLeftModule,
        RiskRightModule,
        RiskRightModule02,
        RiskIconButton,
        RiskTable,
        RiskTableLayout,
        RiskPagination,
    },
})
export default class StockCustomPool extends Vue {
    numberFormat = numberFormat;
    formatterDate = formatterDate;
    formatterTime = formatterTime;
    formatter = formatter;
    formatterNumber = formatterNumber;
    showParamByDocking = showParamByDocking;
    dateFormat = dateFormat;
    timeFormat = timeFormat;
    private leftplaceHolder: string = '编号/名称';
    private leftKey: string = '';
    private rightplaceHolder: string = '证券池编码/名称';
    private rightplaceHolder2: string = '证券代码/名称';

    private rightKey: string = '';
    private rightKey2: string = '';

    private leftHgt: string = '100vh';

    private cutInfo: string = '外部';
    private defaultExpandedKeys: any[] = [1];

    private stGrCustomCode: string = '';

    private stGrCustomCodeList: string[] = [];

    private poolData: any[] = [];

    private treeData: any = [
        {
            label: '外部',
            id: 1,
            children: [],
        },
    ];

    private poolPage: pages = {
        total: 0,
        pageSize: 25,
        currentPage: 1,
    };
    private detailPage: pages = {
        total: 0,
        pageSize: 25,
        currentPage: 1,
    };

    private searchData = {
        textTemp: '',
        typeTemp: '',
    };

    private stockCustomPoolListMsg = {
        url: '/stockCustomPool/stCustomGroup/all',
        returnData: {
            data: [],
        },
        dataKey: 'data',
        title: [
            { name: '自定义证券池编码', val: 'stGrCustomCode', width: 140 },
            { name: '自定义证券池名称', val: 'stGrCustomName', width: 140 },
            { name: '数据来源', val: 'sourceCustomType', width: 120 },
            { name: '添加日期', val: 'dtCtDate', width: 180, sortable: true },
            // { name: '添加时间', val: 'dtCtTime', width: 120 },
            { name: '添加者', val: 'dtCtUser', width: 120 },
            {
                name: '操作',
                type: 'btn',
                btns: [
                    { title: '编辑证券池', type: 'primary', icon: 'el-icon-edit', authCode: 'B_0120' },
                    { title: '删除证券池', type: 'primary', icon: 'el-icon-delete', authCode: 'B_0119' },
                ],
                width: 100,
            },
        ],
        height: '450px',
        // 隐藏页码
        hidePage: false,
        checked: { on: false, option: false },
    };

    private stockCustomPoolDeatailMsg = {
        url: '/stockCustomPool/stock/queryStock/list/' + this.stGrCustomCode,
        returnData: { data: [], total: 0 },
        dataKey: 'data',
        title: [
            { name: '交易市场', val: 'marketCode', width: 120 },
            { name: '证券代码', val: 'stockCode', width: 120 },
            { name: '证券简称', val: 'stockNameSt', width: 120 },
            { name: '证券全称', val: 'stockName', width: 120 },
            { name: '资产类别', val: 'cateGoryCode', width: 120 },
            { name: '证券类型', val: 'stockCustomType', width: 120 },
            { name: '添加日期', val: 'dtCtDate', width: 180 },
            // { name: '添加时间', val: 'dtCtTime', width: 120 },
            { name: '添加者', val: 'dtCtUser', width: 120 },
        ],
        height: '450px',
        // 隐藏页码
        hidePage: false,
        checked: { on: false, option: false },
    };

    private poolForm = {
        stGrCustomCode: '',
        stGrCustomName: '',
    };

    private poolDialogVO: DialogVO = new DialogVO();

    private sourceCustomType: string = '2';

    private stockCodeList: any[] = [];

    private selectedTable: any[] = [];
    private selectedDetailTable: any[] = [];

    private tableData: any[] = [];
    private detailTableData: any[] = [];
    private poolDetailData: any[] = [];

    private categoryTypeSelectData: any[] = []; // 资产类别下拉数据
    private marketCodeSelectData: any[] = []; // 交易市场下拉数据
    private stockTypeSelectData: any[] = []; // 证券类别下拉数据
    private StockType: any = {};
    private MarketType: any = {};
    private CategoryType: any = {};

    private layoutDialog: boolean = false;

    // 全部表格列
    private tableColumns: any[] = [
        { content: '交易市场', id: 'marketCode' },
        { content: '证券代码', id: 'stockCode' },
        { content: '证券简称', id: 'stockNameSt' },
        { content: '证券全称', id: 'stockName' },
        { content: '资产类别', id: 'cateGoryCode' },
        { content: '证券类型', id: 'stockCustomType' },
        { content: '添加日期', id: 'dtCtDate', sortable: true },
        // { content: '添加时间', id: 'dtCtTime' },
        { content: '添加者', id: 'dtCtUser' },
    ];

    // 要显示的表格列
    showFieldList: TFieldItem[] = [];

    // 已选择字段列表
    selectedFieldList: TFieldItem[] = [];
    // 固定字段列表
    fixedFieldList: TFieldItem[] = [
        { content: '交易市场', id: 'marketCode' },
        { content: '证券代码', id: 'stockCode' },
        { content: '证券全称', id: 'stockName' },
    ];
    tabloading: boolean;

    async mounted() {
        if (!showParamByDocking()) {
            this.tableColumns = this.tableColumns.filter(item => item.content != '添加者');
            this.stockCustomPoolDeatailMsg.title = this.stockCustomPoolDeatailMsg.title.filter(item => item.name != '添加者');
            this.stockCustomPoolListMsg.title = this.stockCustomPoolListMsg.title.filter(item => item.name != '添加者');
        }
        this.StockType = DictionConstUtil.ListToPojo(await SGU_CACHE('StockType', '/dict/stockType/list', []));
        this.MarketType = DictionConstUtil.ListToPojo(await SGU_CACHE('MarketType', '/dict/market/list', []));
        this.CategoryType = DictionConstUtil.ListToPojo(await SGU_CACHE('CateGoryCode', '/dict/cateGory/list', []));
        this.queryLayout();

        this.queryStockCustomPoolList();
    }

    // 左边查询
    private submitInput(): void {}

    // 左边栏选择节点
    private clickNode(data: any): void {
        this.cutInfo = data.label;
        this.stGrCustomCode = data.id;
        this.queryPoolDetail();
        // // 重置节点数据
    }

    // 获取自定义证券池列表
    private queryStockCustomPoolList() {
        this.$axios.get(this.stockCustomPoolListMsg.url).then((res: any) => {
            this.stockCustomPoolListMsg.returnData = res;
            this.tableData = res;
            var outside = [];

            for (let item of res) {
                // if (item.sourceCustomType === '2') {
                // disk.push(item);
                let datas = item.stGrCustomCode + '-' + item.stGrCustomName;
                outside.push({ data: item, label: datas, id: item.stGrCustomCode });
                // }
            }
            this.treeData[0].children = outside;
            this.poolPage.currentPage = 1;
            this.currentChange();
            // this.treeData[0].children = [
            //   {
            //     id: '1',
            //     label: 'ceshi',
            //   },
            // ];
        });
    }

    // 证券池分页
    private currentChange(): void {
        this.poolPage.total = this.tableData.length;
        this.poolData = getCurrentPageData(this.tableData, this.poolPage.currentPage, this.poolPage.pageSize);
    }

    // 获取自定义证券池明细列表
    private queryPoolDetail() {
        this.$axios.get(this.stockCustomPoolDeatailMsg.url + '/' + this.stGrCustomCode).then((res: any) => {
            this.detailTableData = res;
            this.detailPage.currentPage = 1;
            this.currentDetailChange();
            // this.stockCustomPoolDeatailMsg.returnData.data = res;
            // this.stockCustomPoolDeatailMsg.returnData.total = res.length;
        });
    }

    // 证券分页
    private currentDetailChange(): void {
        this.detailPage.total = this.detailTableData.length;
        this.poolDetailData = getCurrentPageData(this.detailTableData, this.detailPage.currentPage, this.detailPage.pageSize);
    }

    private searchPool() {
        this.selectedTable = this.handleFilter(this.tableData, this.searchData);
        this.poolPage.total = this.selectedTable.length;
        this.poolData = getCurrentPageData(this.selectedTable, this.poolPage.currentPage, this.poolPage.pageSize);

        this.stockCustomPoolListMsg.returnData.data = getCurrentPageData(this.selectedTable, this.poolPage.currentPage, this.poolPage.pageSize);
    }

    // 证券池筛选数据
    private handleFilter(dataSource: any, param: any): any {
        return dataSource.filter(item => {
            return (
                (!param.textTemp ||
                    item.stGrCustomCode.toLocaleUpperCase().includes(param.textTemp.toLocaleUpperCase()) ||
                    item.stGrCustomName.toLocaleUpperCase().includes(param.textTemp.toLocaleUpperCase())) &&
                (!param.typeTemp || item.sourceCustomType === param.typeTemp)
            );
            // return (
            //     !param.codeName ||
            //     item.stGrCustomCode.toLocaleUpperCase().includes(param.codeName.toLocaleUpperCase()) ||
            //     item.stGrCustomName.toLocaleUpperCase().includes(param.codeName.toLocaleUpperCase())
            // );
        });
    }

    // 查询证券
    private searchPoolDetail() {
        this.selectedDetailTable = this.handleFilterDetail(this.detailTableData, this.rightKey2);
        this.detailPage.total = this.selectedDetailTable.length;
        this.poolDetailData = getCurrentPageData(this.selectedDetailTable, this.detailPage.currentPage, this.detailPage.pageSize);
    }

    // 证券筛选数据
    private handleFilterDetail(dataSource: any, param: any): any {
        if (!param || !dataSource) {
            return dataSource;
        } else {
            return dataSource.filter(
                (item: any) =>
                    (item.stockCode || '').toUpperCase().includes(param.toUpperCase()) ||
                    (item.stockName || '').toUpperCase().includes(param.toUpperCase())
            );
        }
    }

    private handleSelectionChange(val: any) {
        this.stGrCustomCodeList = [];
        for (var i in val) {
            this.stGrCustomCodeList.push(val[i].stGrCustomCode);
        }
    }

    private handleSelectionDetailChange(val: any) {
        this.stockCodeList = [];
        for (var i in val) {
            this.stockCodeList.push(val[i].stockCode);
        }
    }

    // 导出证券池
    private handleExport() {
        downLoadFile({
            url: '/stockCustomPool/export/stock/pool/' + this.sourceCustomType,
            method: 'post',
            data: this.stGrCustomCodeList,
        });
    }

    // 导出证券池明细
    private handleExportDetail() {
        downLoadFile({
            url: '/stockCustomPool/export/stock/' + this.stGrCustomCode,
            method: 'post',
            data: this.stockCodeList,
        });
    }

    async onSubmit(data) {
        await this.queryLayout();
    }

    // 获取页面布局信息
    async queryLayout() {
        this.tabloading = true;
        let resList: any = await new Promise((resolve, reject) => {
            this.$axios('/tableLayout/query/STOCK_CUSTOM_POOL')
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        if (resList) {
            this.selectedFieldList = JSON.parse(resList);
            this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
            // showFieldList.forEach((ele) => {
            //     this.showFieldList.push({ id: ele.id, content: ele.content });
            // });
            this.tabloading = false;
        } else {
            this.showFieldList = this.tableColumns;
            this.tabloading = false;
        }
    }

    handleSort(column): void {
        this.poolPage.currentPage = 1;
        if (column.order == 'dtCtDate') {
            if (column.order == 'ascending') {
                this.tableData.sort((a, b) => a.dtCtDate.localeCompare(b.dtCtDate) || a.dtCtTime.localeCompare(b.dtCtTime));
                this.poolData = getCurrentPageData(this.tableData, this.poolPage.currentPage, this.poolPage.pageSize);
            } else {
                this.tableData.sort((a, b) => b.dtCtDate.localeCompare(a.dtCtDate) || b.dtCtTime.localeCompare(a.dtCtTime));
                this.poolData = getCurrentPageData(this.tableData, this.poolPage.currentPage, this.poolPage.pageSize);
            }
        }
    }
    handleSort1(column): void {
        this.detailPage.currentPage = 1;
        if (column.order == 'dtCtDate') {
            if (column.order == 'ascending') {
                this.detailTableData.sort((a, b) => a.dtCtDate.localeCompare(b.dtCtDate) || a.dtCtTime.localeCompare(b.dtCtTime));
                this.poolDetailData = getCurrentPageData(this.detailTableData, this.detailPage.currentPage, this.detailPage.pageSize);
            } else {
                this.detailTableData.sort((a, b) => b.dtCtDate.localeCompare(a.dtCtDate) || b.dtCtTime.localeCompare(a.dtCtTime));
                this.poolDetailData = getCurrentPageData(this.detailTableData, this.detailPage.currentPage, this.detailPage.pageSize);
            }
        }
    }

    // 获取页面布局信息
    // private queryLayout() {
    //     this.showFieldList = [];
    //     return new Promise((resolve, reject) => {
    //         this.$axios
    //             .get('tableLayout/query/STOCK_CUSTOM_POOL')
    //             .then((res: any) => {
    //                 if (!res) {
    //                     this.showFieldList = JSON.parse(JSON.stringify(this.tableColumns));
    //                     return;
    //                 }
    //                 this.selectedFieldList = JSON.parse(res);
    //                 let showFieldList = this.fixedFieldList.concat(this.selectedFieldList);

    //                 // this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
    //                 showFieldList.forEach(ele => {
    //                     this.showFieldList.push({ id: ele.id, content: ele.content });
    //                 });
    //                 console.log(this.showFieldList);

    //                 resolve(res);
    //             })
    //             .catch(err => {
    //                 reject(err);
    //             });
    //     });
    // }
}
</script>
<style lang="scss" scoped>
.dict-r-slot {
    margin-left: 10px;
}
/deep/ .el-table--border th:first-child .cell {
    padding-left: 6px;
}
</style>
